package com.mf.morefun.ui.moreread;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.AliInfoBean;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.FileBean;
import com.mf.morefun.bean.ListenOriginalBean;
import com.mf.morefun.bean.LocalListenBean;
import com.mf.morefun.bean.MfPicaudioRelListBean;
import com.mf.morefun.bean.MfTpRecordBean;
import com.mf.morefun.bean.MfimgListBean;
import com.mf.morefun.bean.PMUserBean;
import com.mf.morefun.bean.ReadRecordBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.ShareBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestAchievementBean;
import com.mf.morefun.requestbean.RequestSaveHomeWorkBean;
import com.mf.morefun.requestbean.RequestSaveVideoBean;
import com.mf.morefun.requestbean.RequestShareBean;
import com.mf.morefun.requestbean.RequestWorkSaveBean;
import com.mf.morefun.service.RecordMusicService;
import com.mf.morefun.ui.HomePagerActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.DownloadUtils;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.util.UploadUtil;
import com.mf.morefun.util.record.LameMp3Manager;
import com.mf.morefun.util.record.MediaPlayUtil;
import com.mf.morefun.util.record.MediaRecorderListener;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.CustomViewPager;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;
import com.zhcx.zhcxlibrary.widget.ChooseDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
听录音
 */
public class ListenRecordActivity extends BaseBusActivity implements MediaRecorderListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.vp_info)
    CustomViewPager vpInfo;
    @BindView(R.id.pb_speed)
    ProgressBar pbSpeed;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.iv_record)
    ImageView ivRecord;
    @BindView(R.id.iv_record_show)
    ImageView ivRecordShow;
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.voice_recond)
    ImageView voiceRecond;
    @BindView(R.id.iv_submit)
    ImageView ivSubmit;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    private String bookId = "";
    private RoundProcessDialog dialog;
    private SPUtils mSPUtils;
    private List<View> viewContains = new ArrayList<View>();//viewpager容器
    private int currentPosition = 0;
    private int currentSelectPosition = 0;
    private MyPagerAdapter myPagerAdapter;
    private int totalPage = 0;
    private RecordMusicService mRecordMusicService = null;
    private boolean isPlay = true;
    private int currentUploadPosition = 0;
    private List<FileBean> fileList = new ArrayList<>();
    private String type = "";
    private AnimationDrawable animationDrawable;
    private String mfRecordId = "";
    private String bookName = "";
    private List<LocalListenBean> mLocalViewList = new ArrayList<>();//重新创建一个集合来存排序好的集合
    private DbManager manager;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private String contextId = "";
    private String userId = "";
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;
    private boolean isAutoPause = false;//是否是播放第一页自动暂停的还是点击暂停的

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_listenrecord;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        userId = getIntent().getStringExtra(Configuration.USERID);

        //清空缓存
        File file = new File(getBasePath());

        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files)
        {
            f.delete();
        }

        powerManager = (PowerManager)this.getSystemService(this.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock2");
        mSPUtils = new SPUtils(getApplicationContext());
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPUtils.getString(Configuration.USERPHONE), mSPUtils.getString(Configuration.USERPASSWORD));
        }
        contextId = getIntent().getStringExtra("CONTEXTID");
        animationDrawable = (AnimationDrawable) voiceRecond
                .getBackground();
        manager = x.getDb(MoreFunApplication.daoConfig);
        EventBus.getDefault().register(this);
        dialog = new RoundProcessDialog(ListenRecordActivity.this, "");
        bookId = getIntent().getStringExtra("BOOKID");
        type = getIntent().getStringExtra("TYPE");
        mfRecordId = getIntent().getStringExtra("MFRECORDID");//作业id
        if (StringUtils.isEmpty(getIntent().getStringExtra("BOOKNAME"))) {
            bookName = "" + System.currentTimeMillis();
        } else {
            bookName = getIntent().getStringExtra("BOOKNAME") + "record";
        }
        if (!StringUtils.isEmpty(bookId)) {
            initGetRead();
        }
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("POSTRECORD");
        registerReceiver(mReceiver, mFilter);
        ivSubmit.getBackground().setAlpha(100);
        vpInfo.setScanScroll(true);

        initGetAliInfo();
    }

    private void initGetAliInfo() {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.GETALIINFOV2);


        /*params.setBodyContent("{\n" +
                " \n" +
                "}");
        */

        PMUserBean.CountryBean countrybean = new PMUserBean.CountryBean();
        countrybean.setId( MoreFunApplication.loginBean.getResult().getCountry().getId());
        params.setBodyContent(JSON.toJSONString(countrybean));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    AliInfoBean aliInfoBean = JSON.parseObject(result, AliInfoBean.class);
                    if (aliInfoBean.getStatusCode() == 200) {
                        mSPUtils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYID, aliInfoBean.getAccessKeyId());
                        mSPUtils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYSECRET, aliInfoBean.getAccessKeySecret());
                        mSPUtils.putString(com.mf.morefun.constant.Configuration.SECURITYTOKEN, aliInfoBean.getSecurityToken());

                        mSPUtils.putString(com.mf.morefun.constant.Configuration.ENDPOINT, aliInfoBean.getEndPoint());
                        mSPUtils.putString(com.mf.morefun.constant.Configuration.BUCKETNAME, aliInfoBean.getBucketName());
                        mSPUtils.putString(com.mf.morefun.constant.Configuration.BUCKETDOMAIN, aliInfoBean.getBucketDomain());
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("POSTRECORD")){
                if (type.equals("1")){
                    //先保存
                    saveData();
                }else {
                    initSaveVideo("");
                }
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (null != mRecordMusicService){
                mRecordMusicService.pause();
            }
            ivPlay.setImageResource(R.mipmap.bofang);
            isPlay = false;
            if (null != wakeLock){
                wakeLock.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (null != wakeLock){
                wakeLock.acquire();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    protected void initData() {
        if (isHaveRecord()) {
            ivVoice.setImageResource(R.drawable.play_record_btn_press);
            ivSubmit.setImageResource(R.mipmap.sure_bg);
        } else {
            ivVoice.setImageResource(R.drawable.play_record_btn_normal);
            ivSubmit.setImageResource(R.drawable.submit_record_btn_normal);
        }
    }

    private void initGetRead() {
        if (null != dialog && !dialog.isShow()) {
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.MOREREADRECORD);
        RequestAchievementBean requestAchievementBean = new RequestAchievementBean();
        requestAchievementBean.setId(bookId);
        params.setBodyContent(JSON.toJSONString(requestAchievementBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            ListenOriginalBean listenOriginalBean = JSON.parseObject(resultBean.getResult(), ListenOriginalBean.class);
                            if (!StringUtils.isEmpty(listenOriginalBean.getImgList()) && !StringUtils.isEmpty(listenOriginalBean.getImgAudioRelList())) {
                                List<MfimgListBean> mfimgListBeanList = JSON.parseArray(listenOriginalBean.getImgList(), MfimgListBean.class);
                                List<MfPicaudioRelListBean> mfPicaudioRelListBeanList = JSON.parseArray(listenOriginalBean.getImgAudioRelList(), MfPicaudioRelListBean.class);
                                //两个集合必须都不为空
                                if (null != mfimgListBeanList && mfimgListBeanList.size() > 0 && null != mfPicaudioRelListBeanList && mfPicaudioRelListBeanList.size() > 0) {
                                    //必须等于  因为一对一
                                    if (mfimgListBeanList.size() == mfPicaudioRelListBeanList.size()) {
                                        //组装成自己的对象
                                        List<LocalListenBean> mLocalList = new ArrayList<>();
                                        for (int i = 0; i < mfimgListBeanList.size(); i++) {
                                            LocalListenBean localListenBean = new LocalListenBean();
                                            localListenBean.setImageUrl(mfimgListBeanList.get(i).getAddress());
                                            localListenBean.setLocalListenUrl("");
                                            if (null != listenOriginalBean.getAudioList()) {
                                                localListenBean.setNetListenUrl(listenOriginalBean.getAudioList().get(0).getAddress());
                                            }
                                            localListenBean.setVodStart(mfPicaudioRelListBeanList.get(i).getVodStart());
                                            localListenBean.setMusicName(bookName);
                                            localListenBean.setId(0);
                                            mLocalList.add(localListenBean);
                                        }
                                        //先判断是否要去下载 本地有了就不需要下载
                                        showLocalList(mLocalList);


                                    }
                                }
                            } else {
                                ToastUtils.show(getApplicationContext(), "数据为空", 100);
                            }
                        } else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void showLocalList(List<LocalListenBean> mLocalList) {
        try {
            List<LocalListenBean> localList = manager.selector(LocalListenBean.class).where("netListenUrl", "==", mLocalList.get(0).getNetListenUrl()).findAll();
            if (null != localList && localList.size() > 0) {
                manager.delete(localList);
                removeDuplicate(localList);
                List<LocalListenBean> mNeedList = new ArrayList<>();
                for (int i = 0; i < localList.size(); i++) {
                    manager.save(localList.get(i));
                    if (mLocalList.get(0).getNetListenUrl().equals(localList.get(i).getNetListenUrl())) {
                        mNeedList.add(localList.get(i));//拿到存在本地的
                    }
                }
                if (null != mNeedList && mNeedList.size() > 0) {
                    //这里拿到集合可以直接播放
                    ablePlay(mNeedList);
                } else {
                    //这里需要去下载
                    needDownload(mLocalList);
                }
            } else {
                //这里肯定是要去下载
                needDownload(mLocalList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeDuplicate(List<LocalListenBean> localMessageList) {
        List<LocalListenBean> newList = new ArrayList<LocalListenBean>();
        for (LocalListenBean msg : localMessageList) {
            if (newList.size() > 0) {
                if (!isSure(newList, msg.getImageUrl())) {
                    newList.add(msg);
                }
            } else {
                newList.add(msg);
            }
        }
        localMessageList.clear();
        localMessageList.addAll(newList);
    }

    private boolean isSure(List<LocalListenBean> newList, String imageUrl) {
        boolean isHave = false;
        for (LocalListenBean newMsg : newList) {
            if (newMsg.getImageUrl().equals(imageUrl)) {
                isHave = true;
            }
        }
        return isHave;
    }


    //需要去下载的集合
    private void needDownload(List<LocalListenBean> mLocalList) {
        DownloadUtils.getsInstance().setListener(new DownloadUtils.OnDownloadListener() {
            @Override
            public void onDowload(String mp3Url) {
                //把本地地址加上 存进入数据库
                insertDb(mp3Url, mLocalList);
                ablePlay(mLocalList);
            }

            @Override
            public void onFailed(String error) {
                ToastUtils.show(getApplicationContext(), "下载失败", 100);
            }
        }).download(mLocalList.get(0));
    }

    private void insertDb(String mp3Url, List<LocalListenBean> mLocalList) {
        try {
            for (int i = 0; i < mLocalList.size(); i++) {
                mLocalList.get(i).setLocalListenUrl(mp3Url);
                manager.save(mLocalList.get(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //能够播放的集合   但是还要调整集合顺序
    private void ablePlay(List<LocalListenBean> mNeedList) {
        //先初始化一个集合  排序
        getVodStartList(mNeedList, mLocalViewList);
        //同时还要展示viewpager
        showViewPager(mLocalViewList);
    }

    private void getVodStartList(List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        double mVodArray[] = new double[mNeedList.size()];
        for (int i = 0; i < mNeedList.size(); i++) {
            mVodArray[i] = mNeedList.get(i).getVodStart();
        }
        //冒泡排序一下
        bubbleSort(mVodArray);
        for (int i = 0; i < mVodArray.length; i++) {
            //取到对象
            getNeedBean(mVodArray[i], mNeedList, mLocalList);
        }
    }

    private void getNeedBean(double vod, List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        for (int i = 0; i < mNeedList.size(); i++) {
            if (vod == mNeedList.get(i).getVodStart()) {
                mLocalList.add(mNeedList.get(i));
            }
        }
    }

    private void bubbleSort(double[] mVodArray) {
        for (int i = 0; i < mVodArray.length - 1; i++) {
            for (int j = 0; j < mVodArray.length - 1 - i; j++) {
                if (mVodArray[j] > mVodArray[j + 1]) {
                    double temp;
                    temp = mVodArray[j];
                    mVodArray[j] = mVodArray[j + 1];
                    mVodArray[j + 1] = temp;
                }
            }
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (null != mRecordMusicService) {
            mRecordMusicService.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mRecordMusicService) {
            mRecordMusicService.stop();
        }
        stopPlay();
        stopRecord();
        MoreFunApplication.isOut = true;//退出
        EventBus.getDefault().unregister(this);
        if (null != mSendStartOrFlowerNet) {
            mSendStartOrFlowerNet.stopAnim();
        }
    }

    //接受RecordMusicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if (message.getType() == 0) {//播放完成发过来的消息
            if (isPlay) {
                ivPlay.setImageResource(R.mipmap.bofang);
            }
        } else if (message.getType() == 1) {//播放失败发过来的消息
            MoreFunApplication.isOut = true;
            if (isPlay) {
                ivPlay.setImageResource(R.mipmap.bofang);
            }
            ToastUtils.show(getApplicationContext(), "音乐文件加载失败", 100);
        } else if (message.getType() == 101) {

           // String host = Configuration.OOSROOT;// "http://morefunreadingproduct.oss-cn-shanghai.aliyuncs.com/";

            String host =  mSPUtils.getString(Configuration.BUCKETDOMAIN);

            if (fileList.size() > 0) {
                fileList.get(currentUploadPosition).setFilePath(host + message.getFileName());
                fileList.get(currentUploadPosition).setSwitchTime(DateUtils.getSecond(formatTime(message.getTime())));
                if (currentUploadPosition == (fileList.size() - 1)) {
                    //调接口上传服务器
                    if (null != mLocalViewList && mLocalViewList.size() > 0) {
                        //作品  和作业
                        initUpload(fileList);
                    }
                } else {
                    currentUploadPosition++;
                    startUpload(fileList);
                }
            }
        } else if (message.getType() == 102) {
            ToastUtils.show(getApplicationContext(), message.getFileName(), 100);
            if (fileList.size() > 0) {
                fileList.get(currentUploadPosition).setSwitchTime(DateUtils.getSecond(formatTime(message.getTime())));
                if (currentUploadPosition == (fileList.size() - 1)) {
                    //调接口上传服务器
                    if (null != mLocalViewList && mLocalViewList.size() > 0) {
                        initUpload(fileList);
                    }
                } else {
                    currentUploadPosition++;
                    startUpload(fileList);
                }
            }
        } else if(message.getType() == 1088){//错误的
            try {
                showFinishPop(message.getFileName(), message.getType());
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(message.getType() == 1099){//正常的
            try {
                showFinishPop(message.getFileName(), message.getType());
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            if (null != mRecordMusicService && null != mRecordMusicService.player && mRecordMusicService.player.isPlaying()) {
                long second = mRecordMusicService.getCurrentProgress();
                int position = 0;
                if (null != vpInfo){
                    position = vpInfo.getCurrentItem();
                    currentPosition = position;
                }else {
                    position = currentPosition;
                }
                //获得比例
                if (null != mLocalViewList && mLocalViewList.size() > 0) {
                    for (int i = 0; i < mLocalViewList.size(); i++) {
                        if (i == 0) {
                            if (second >= 0 && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                                currentPosition = 0;
                            }
                        } else if (second >= (int) (mLocalViewList.get(i - 1).getVodStart() * 1000) && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                            currentPosition = i;
                        }
                    }
                }
                if (position != currentPosition) {
                    ivPlay.setImageResource(R.mipmap.bofang);
                    mRecordMusicService.pause();
                    isPlay = false;
                    isAutoPause = true;
                }
            }
        }
    }

    private String formatTime(long time) {
        return formatTime("mm:ss", time);
    }

    private String formatTime(String pattern, long milli) {
        int m = (int) (milli / android.text.format.DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / android.text.format.DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }

    private void initUpload(List<FileBean> mNetUrl) {
        String url = "";
        if (type.equals("1")){
            url = Configuration.HOST + Configuration.WORKSAVE;
        }else {
            url = Configuration.HOST + Configuration.HOMEWORKRECORDSAVE;
        }
        RequestParams params = new RequestParams(url);
        if (type.equals("1")){
            RequestWorkSaveBean requestWorkSaveBean = new RequestWorkSaveBean();
            requestWorkSaveBean.setType("1");
            requestWorkSaveBean.setAudio(mLocalViewList.get(0).getNetListenUrl());
            RequestWorkSaveBean.UserBean userBean = new RequestWorkSaveBean.UserBean();
            userBean.setId(userId);
            RequestWorkSaveBean.BookBean bookBean = new RequestWorkSaveBean.BookBean();
            bookBean.setId(bookId);
            List<RequestWorkSaveBean.MfUserImgRecordListBean> mList = new ArrayList<>();
            for (int i = 0; i < mNetUrl.size(); i++) {
                if (!StringUtils.isEmpty(mNetUrl.get(i).getFilePath())) {
                    RequestWorkSaveBean.MfUserImgRecordListBean mfUserImgRecordListBean = new RequestWorkSaveBean.MfUserImgRecordListBean();
                    mfUserImgRecordListBean.setAudio(mNetUrl.get(i).getFilePath());
                    mfUserImgRecordListBean.setAddress(mNetUrl.get(i).getAddress());
                    mfUserImgRecordListBean.setDirection("1");
                    mfUserImgRecordListBean.setType("1");
                    mfUserImgRecordListBean.setSwitch_time(mNetUrl.get(i).getSwitchTime() + "");
                    mList.add(mfUserImgRecordListBean);
                }
            }
            requestWorkSaveBean.setBook(bookBean);
            requestWorkSaveBean.setUser(userBean);
            requestWorkSaveBean.setMfUserImgRecordList(mList);
            params.setBodyContent(JSON.toJSONString(requestWorkSaveBean));
        }else {
            RequestSaveHomeWorkBean requestWorkSaveBean = new RequestSaveHomeWorkBean();
            requestWorkSaveBean.setType("2");
            requestWorkSaveBean.setAudio(mLocalViewList.get(0).getNetListenUrl());
            RequestSaveHomeWorkBean.UserBean userBean = new RequestSaveHomeWorkBean.UserBean();
            userBean.setId(userId);
            RequestSaveHomeWorkBean.BookBean bookBean = new RequestSaveHomeWorkBean.BookBean();
            bookBean.setId(bookId);
            RequestSaveHomeWorkBean.MftpRecordBean mftpRecordBean = new RequestSaveHomeWorkBean.MftpRecordBean();
            mftpRecordBean.setId(mfRecordId);
            List<RequestSaveHomeWorkBean.MfUserImgRecordListBean> mList = new ArrayList<>();
            for (int i = 0; i < mNetUrl.size(); i++) {
                if (!StringUtils.isEmpty(mNetUrl.get(i).getFilePath())) {
                    RequestSaveHomeWorkBean.MfUserImgRecordListBean mfUserImgRecordListBean = new RequestSaveHomeWorkBean.MfUserImgRecordListBean();
                    mfUserImgRecordListBean.setAudio(mNetUrl.get(i).getFilePath());
                    mfUserImgRecordListBean.setAddress(mNetUrl.get(i).getAddress());
                    mfUserImgRecordListBean.setDirection("1");
                    mfUserImgRecordListBean.setType("2");
                    mfUserImgRecordListBean.setSwitch_time(mNetUrl.get(i).getSwitchTime() + "");
                    mList.add(mfUserImgRecordListBean);
                }
            }
            requestWorkSaveBean.setBook(bookBean);
            requestWorkSaveBean.setUser(userBean);
            requestWorkSaveBean.setMftpRecord(mftpRecordBean);
            requestWorkSaveBean.setMfUserImgRecordList(mList);
            params.setBodyContent(JSON.toJSONString(requestWorkSaveBean));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                if (!StringUtils.isEmpty(result)) {
                    if (type.equals("1")){
                        ReadRecordBean readRecordBean = JSON.parseObject(result, ReadRecordBean.class);
                        if (readRecordBean.getErrorCode() == 0) {
                            contextId = readRecordBean.getResult().getMfWork().getId();
                            //弹出一个框
                            mSendStartOrFlowerNet = new SendStarOrFlowerNet(ListenRecordActivity.this, lyContent);
                            mSendStartOrFlowerNet.initGetFlower(30
                                    , mSPUtils.getString(Configuration.USERID),
                                    bookId,
                                    "1", "1"
                            );
                        }
                        ToastUtils.show(getApplicationContext(), readRecordBean.getMessage(), 100);
                    }else {
                        ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                        if (resultBean.getErrorCode() == 0) {
                            //弹出一个框
                            mSendStartOrFlowerNet = new SendStarOrFlowerNet(ListenRecordActivity.this, lyContent);
                            mSendStartOrFlowerNet.initGetFlower(30
                                    , mSPUtils.getString(Configuration.USERID),
                                    bookId,
                                    "1", "2"
                            );
                        }
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow mUserPop;

    private void showFinishPop(String message, int types) {
        try {
            View view = LayoutInflater.from(ListenRecordActivity.this).inflate(R.layout.layout_popfinish, null);
            RelativeLayout rlBg = view.findViewById(R.id.rl_bg);
            rlBg.getBackground().setAlpha(100);
            TextView tv_back = view.findViewById(R.id.tv_back);
            TextView tv_share = view.findViewById(R.id.tv_share);
            TextView tv_unit = view.findViewById(R.id.tv_unit);
            TextView tv_num = view.findViewById(R.id.tv_num);
            TextView tv_type = view.findViewById(R.id.tv_type);
            if (types == 1088){
                tv_type.setText(message);
                tv_unit.setVisibility(View.GONE);
                tv_num.setVisibility(View.GONE);
            }else {
                tv_unit.setVisibility(View.VISIBLE);
                tv_num.setVisibility(View.VISIBLE);
                tv_type.setText("本次获得" + message + "奖励");
                tv_num.setText(30 + "");
            }
            tv_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mUserPop.dismiss();
                    mUserPop = null;
                    Intent intent = new Intent();
                    if (!type.equals("1")){
                        intent.putExtra("MFRECORDID", mfRecordId);
                    }
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
            tv_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mUserPop.dismiss();
                    mUserPop = null;
                    initShareHttp();
                }
            });
            mUserPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mUserPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mUserPop.setBackgroundDrawable(new BitmapDrawable());
            mUserPop.setFocusable(true);
            mUserPop.update();
            mUserPop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mUserPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mUserPop.dismiss();
                    mUserPop = null;
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void initShareHttp() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SHARE);
        RequestShareBean requestShareBean = new RequestShareBean();
        requestShareBean.setUserID(mSPUtils.getString(Configuration.USERID));
        requestShareBean.setContextID(contextId);
        requestShareBean.setContextType(getIntent().getStringExtra("CONTEXTTYPE"));
        requestShareBean.setShareType("2");//1为图片  2为链接
        requestShareBean.setMediaType(getIntent().getStringExtra("MEDIATYPE"));
        params.setBodyContent(JSON.toJSONString(requestShareBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            ShareBean shareBean = JSON.parseObject(resultBean.getResult(), ShareBean.class);
                            try {
                                showSharePop(shareBean);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow sharePop;

    private void showSharePop(ShareBean shareBean) {
        if (sharePop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_sharepop, null);
            // 这里启动头像
            RelativeLayout rl_bg = (RelativeLayout) view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                }
            });
            LinearLayout ll_pengyou = view.findViewById(R.id.ll_pengyouquan);
            ll_pengyou.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                    if (checkInstalled(0)) {
                        showShare(0, shareBean);
                    } else {
                        ToastUtils.show(ListenRecordActivity.this, "请先安装微信", 100);
                    }
                }
            });
            LinearLayout ll_wechat = view.findViewById(R.id.ll_wechat);
            ll_wechat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                    if (checkInstalled(0)) {
                        showShare(1, shareBean);
                    } else {
                        ToastUtils.show(ListenRecordActivity.this, "请先安装微信", 100);
                    }
                }
            });
            LinearLayout ll_wechatcollect = view.findViewById(R.id.ll_wechatcollect);
            ll_wechatcollect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                    if (checkInstalled(0)) {
                        showShare(2, shareBean);
                    } else {
                        ToastUtils.show(ListenRecordActivity.this, "请先安装微信", 100);
                    }
                }
            });
            int h = ListenRecordActivity.this.getWindowManager().getDefaultDisplay().getHeight();
            sharePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            sharePop.setFocusable(true);
            sharePop.setOutsideTouchable(true);
            sharePop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            sharePop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            ListenRecordActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = ListenRecordActivity.this.getWindow().getDecorView().getHeight();
            sharePop.showAtLocation(ListenRecordActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, winHeight - rect.bottom);
        }
    }

    private boolean checkInstalled(int index) {
        boolean isInstall = false;
        switch (index) {
            case 0://微信
                isInstall = isInstallWx("com.tencent.mm");
                break;
            case 1://QQ
                isInstall = isInstallWx("com.tencent.mobileqq");
                break;
        }
        return isInstall;
    }

    /**
     * 是否安装微信
     */
    public boolean isInstallWx(String packageNames) {
        try {
            PackageManager manager = ListenRecordActivity.this.getPackageManager();
            List<PackageInfo> list = manager.getInstalledPackages(0);
            List<String> mList = new ArrayList<String>();
            if (null != list && list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    mList.add(list.get(i).packageName);
                }
            }
            if (null != mList && mList.size() != 0) {
                return mList.contains(packageNames);
            } else {
                return false;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return false;
    }

    private void showShare(int index, ShareBean shareBean) {
        if (null != shareBean) {
            UMImage image = new UMImage(ListenRecordActivity.this, shareBean.getCover());//资源文件
            String shareUrl = shareBean.getLinkAddress();
            UMWeb web = new UMWeb(shareUrl);
            web.setTitle(shareBean.getContext());//标题
            web.setThumb(image);  //缩略图
            web.setDescription(shareBean.getName());//描述
            switch (index) {
                case 0://朋友群
                    new ShareAction(ListenRecordActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
                case 1://微信
                    new ShareAction(ListenRecordActivity.this).setPlatform(SHARE_MEDIA.WEIXIN)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
                case 2://微信收藏
                    new ShareAction(ListenRecordActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_FAVORITE)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
            }
        }
    }


    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(ListenRecordActivity.this, "分享成功", Toast.LENGTH_LONG).show();
            mSendStartOrFlowerNet = new SendStarOrFlowerNet(ListenRecordActivity.this, lyContent);
            mSendStartOrFlowerNet.initGetFlower(10
                    , mSPUtils.getString(Configuration.USERID),
                    bookId,
                    "2", "7"
            );
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ListenRecordActivity.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ListenRecordActivity.this, "取消分享", Toast.LENGTH_LONG).show();

        }
    };

    private void nextPlay() {
        if (currentPosition < (totalPage - 1)) {
            currentPosition++;
            vpInfo.setCurrentItem(currentPosition);
        } else {
            ivPlay.setImageResource(R.mipmap.bofang);
        }
    }

    private void showViewPager(List<LocalListenBean> mLocalList) {
        viewContains.clear();
        currentSelectPosition = 0;
        setPagerAdapter();
        setPagerListener();
        if (null != mLocalList && mLocalList.size() > 0) {
            totalPage = mLocalList.size();
            for (int i = 0; i < mLocalList.size(); i++) {
                View view = LayoutInflater.from(ListenRecordActivity.this).inflate(R.layout.layout_advertisement, null);
                ImageView imageView = view.findViewById(R.id.iv_image);
                Glide.with(getApplicationContext()).load(mLocalList.get(i).getImageUrl()).into(imageView);
                viewContains.add(view);
            }
            myPagerAdapter.notifyDataSetChanged();
            setProgressBar(vpInfo.getCurrentItem());
            MoreFunApplication.isOut = false;//这里是进入
            Intent intent = new Intent();
            intent.setAction("GETMUSICPOSITION");
            intent.setPackage("com.mf.morefun"); //指定启动的是那个应用（lq.cn.twoapp）中的Action(b.aidl.DownLoadService)指向的服务组件
            startService(intent);
            mRecordMusicService = new RecordMusicService(mLocalViewList.get(0).getLocalListenUrl(), ListenRecordActivity.this);
            mRecordMusicService.play();
            ivPlay.setImageResource(R.mipmap.zanting);

            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }

        } else {
            ToastUtils.show(getApplicationContext(), "数据为空", 100);
        }
    }

    private void setProgressBar(int mPosition) {
        int index = (100 / totalPage);
        if (mPosition == (totalPage - 1)) {
            pbSpeed.setProgress(100);
        } else {
            pbSpeed.setProgress(index * (mPosition + 1));
        }
    }

    private void setPagerListener() {
        vpInfo.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                try {
                    if (currentSelectPosition > position) {
                        currentSelectPosition = position;
                        int mPosition = 0;
                        if (position == 0) {
                            mPosition = position;
                        } else {
                            mPosition = position - 1;
                        }
                        stopRecord();
                        stopPlay();
                        if (isHaveRecord()) {
                            ivVoice.setImageResource(R.drawable.play_record_btn_press);
                        } else {
                            ivVoice.setImageResource(R.drawable.play_record_btn_normal);
                        }
                        setProgressBar(position);//更新进度条
                        if (null != mRecordMusicService && null != mRecordMusicService.player && isPlay) {
                            if (position == 0) {
                                mRecordMusicService.player.seekTo(0);
                            } else {
                                mRecordMusicService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                            }
                            ivPlay.setImageResource(R.mipmap.zanting);
                            mRecordMusicService.goPlay();
                        }else {
                            isAutoPause = true;
                        }
                    } else {
                        if (isHaveRecord()) {
                            currentSelectPosition = position;
                            int mPosition = 0;
                            if (position == 0) {
                                mPosition = position;
                            } else {
                                mPosition = position - 1;
                            }
                            stopRecord();
                            stopPlay();
                            if (isHaveRecord()) {
                                ivVoice.setImageResource(R.drawable.play_record_btn_press);
                            } else {
                                ivVoice.setImageResource(R.drawable.play_record_btn_normal);
                            }
                            setProgressBar(position);//更新进度条
                            if (null != mRecordMusicService && null != mRecordMusicService.player && isPlay) {
                                if (position == 0) {
                                    mRecordMusicService.player.seekTo(0);
                                } else {
                                    mRecordMusicService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                                }
                                ivPlay.setImageResource(R.mipmap.zanting);
                                mRecordMusicService.goPlay();
                            }else {
                                isAutoPause = true;
                            }
                        } else {
                            vpInfo.setCurrentItem(currentSelectPosition);
                            stopRecord();
                            stopPlay();
                            setProgressBar(vpInfo.getCurrentItem());//更新进度条
                            ToastUtils.show(getApplicationContext(), "请先录音", 100);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    vpInfo.setCurrentItem(currentSelectPosition);
                    stopRecord();
                    stopPlay();
                    setProgressBar(vpInfo.getCurrentItem());//更新进度条
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onRecorderFinish(int status, String path) {
        mHandler.sendEmptyMessage(1010);
    }


    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return viewContains.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//                ((ViewPager) container).removeView(viewContains.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= viewContains.size();
            if (position < 0) {
                position = viewContains.size() + position;
            }
            View view = viewContains.get(position);
            // 如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }


    private void setPagerAdapter() {
        myPagerAdapter = new MyPagerAdapter();
        vpInfo.setAdapter(myPagerAdapter);
    }


    @OnClick({R.id.iv_back, R.id.iv_play, R.id.iv_record, R.id.iv_voice, R.id.iv_submit, R.id.voice_recond, R.id.iv_record_show})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                BackIdeaPop pop = new BackIdeaPop(ListenRecordActivity.this);
                pop.showPop("确定退出当前页面吗？", 3, 0);
                break;
            case R.id.iv_play:
                if (null != mRecordMusicService && null != mRecordMusicService.player) {
                    if (!mRecordMusicService.player.isPlaying()) {
                        isPlay = true;
                        ivPlay.setImageResource(R.mipmap.zanting);
                        if (isAutoPause){
                            int mPosition = 0;
                            if (vpInfo.getCurrentItem() == 0) {
                                mPosition = vpInfo.getCurrentItem();
                            } else {
                                mPosition = vpInfo.getCurrentItem() - 1;
                            }
                            if (vpInfo.getCurrentItem() == 0) {
                                mRecordMusicService.player.seekTo(0);
                            } else {
                                mRecordMusicService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                            }
                            mRecordMusicService.player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                                @Override
                                public void onSeekComplete(MediaPlayer mp) {
//                                    mRecordMusicService.goPlay();
                                    mHandler.sendEmptyMessage(100);
                                }
                            });
                        }else {
//                            mRecordMusicService.goPlay();
                            mHandler.sendEmptyMessage(100);
                        }
                        stopRecord();
                        stopPlay();
                    } else if (mRecordMusicService.player.isPlaying()) {
                        isPlay = false;
                        mRecordMusicService.pause();
                        ivPlay.setImageResource(R.mipmap.bofang);
                        isAutoPause = false;
                    }
                }
                break;
            case R.id.iv_record://开始录音
                if (null != mRecordMusicService && null != mRecordMusicService.player && mRecordMusicService.player.isPlaying()) {
                    mRecordMusicService.pause();
                    isPlay = false;
                    ivPlay.setImageResource(R.mipmap.bofang);
                }
                ivRecord.setVisibility(View.GONE);
                ivRecordShow.setVisibility(View.VISIBLE);
                ivRecordShow.getDrawable().setLevel(0);
                startRecord();
                stopPlay();
                break;
            case R.id.iv_record_show://暂停录音
                if (null != mRecordMusicService && null != mRecordMusicService.player) {
                    ivPlay.setImageResource(R.mipmap.bofang);
                }
                stopRecord();
                break;
            case R.id.iv_voice://播放录音文件  判断是否有播放的录音文件
                if (null != mRecordMusicService && null != mRecordMusicService.player && mRecordMusicService.player.isPlaying()) {
                    mRecordMusicService.pause();
                    isPlay = false;
                    ivPlay.setImageResource(R.mipmap.bofang);
                }
                if (isHaveRecord()) {
                    stopRecord();
                    ivVoice.setVisibility(View.GONE);
                    voiceRecond.setVisibility(View.VISIBLE);
                    if (null != animationDrawable) {
                        animationDrawable.start();
                    }
                    playInModeStream();
                }
                break;
            case R.id.iv_submit://转码  转成MP3
                BackIdeaPop backIdeaPop = new BackIdeaPop(ListenRecordActivity.this);
                backIdeaPop.showPop("确定提交该录音作业吗？", 7, 0);
                break;
            case R.id.voice_recond://点击暂停
                if (null != mRecordMusicService && null != mRecordMusicService.player) {
                    isPlay = false;
                    ivPlay.setImageResource(R.mipmap.bofang);
                }
                stopPlay();
                break;
        }
    }

    private void saveData(){
        currentUploadPosition = 0;
        //搜寻
        if (null != dialog && !dialog.isShow()) {
            dialog.setMessage("正在上传文件...");
            dialog.show();
        }
        if (mLocalViewList.size() > 0) {
            fileList.clear();
            for (int i = 0; i < mLocalViewList.size(); i++) {
                File file = new File(getBasePath() + "/" + i + bookId + "record.mp3");
                if (file.exists()) {
                    FileBean fileBean = new FileBean();
                    fileBean.setFileName(i + bookId + "record.mp3");
                    fileBean.setFilePath(getBasePath() + "/" + i + bookId + "record.mp3");
                    fileBean.setAddress(mLocalViewList.get(i).getImageUrl());
                    fileList.add(fileBean);
                }
            }
            if (fileList.size() > 0) {
                startUpload(fileList);
            }
        } else {
            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }
        }
    }

    private void initSaveVideo(String videoPaths) {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.SAVEVIDEO);
        RequestSaveVideoBean requestSaveVideoBean = new RequestSaveVideoBean();
        requestSaveVideoBean.setAudio(videoPaths);
        requestSaveVideoBean.setType("3");
        if (StringUtils.isEmpty(getIntent().getStringExtra("TPBUS"))) {
            requestSaveVideoBean.setTpBus("");
        } else {
            requestSaveVideoBean.setTpBus(getIntent().getStringExtra("TPBUS"));
        }
        RequestSaveVideoBean.TpDetailBean tpDetailBean = new RequestSaveVideoBean.TpDetailBean();
        if (StringUtils.isEmpty(getIntent().getStringExtra("TPDETAILID"))) {
            tpDetailBean.setId("");
        } else {
            tpDetailBean.setId(getIntent().getStringExtra("TPDETAILID"));
        }
        requestSaveVideoBean.setTpDetail(tpDetailBean);
        RequestSaveVideoBean.UserBean userBean = new RequestSaveVideoBean.UserBean();
        userBean.setId(userId);
        requestSaveVideoBean.setUser(userBean);
        RequestSaveVideoBean.ClassBelongBean classBelongBean = new RequestSaveVideoBean.ClassBelongBean();
        classBelongBean.setId(getIntent().getStringExtra("CLASSID"));
        requestSaveVideoBean.setClassBelong(classBelongBean);
        RequestSaveVideoBean.TpBean tpBean = new RequestSaveVideoBean.TpBean();
        tpBean.setId(getIntent().getStringExtra("TP"));
        requestSaveVideoBean.setTp(tpBean);
        params.setBodyContent(JSON.toJSONString(requestSaveVideoBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())){
                            MfTpRecordBean mfTpRecordBean = JSON.parseObject(resultBean.getResult(), MfTpRecordBean.class);
                            mfRecordId = mfTpRecordBean.getId();
                            contextId = mfTpRecordBean.getTpBus();
                            saveData();
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void startUpload(List<FileBean> fileList) {
        UploadUtil uploadUtil = new UploadUtil();
        uploadUtil.uploadFile(ListenRecordActivity.this,
                mSPUtils.getString(Configuration.ACCESSKEYID),
                mSPUtils.getString(Configuration.ACCESSKEYSECRET),
                mSPUtils.getString(Configuration.SECURITYTOKEN),
                mSPUtils.getString(Configuration.ENDPOINT),
                mSPUtils.getString(Configuration.BUCKETNAME),

                fileList.get(currentUploadPosition).getFileName(),
                fileList.get(currentUploadPosition).getFilePath(), false);
        fileList.get(currentUploadPosition).setFilePath("");
    }

    //File.separator +
    private boolean isHaveRecord() {
        File file = new File(getBasePath() + "/" + currentSelectPosition + bookId + "record.mp3");
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    private int count;

    //开始录音
    public void startRecord() {
        try {
            final File file = new File(getBasePath() + "/" + currentSelectPosition + bookId + "record.mp3");
            if (!file.mkdirs()) {
                Log.e("record", "Directory not created");
            }
            if (file.exists()) {
                file.delete();
            }
            LameMp3Manager.instance.startRecorder(getBasePath() + "/" + currentSelectPosition + bookId + "record.mp3");
            LameMp3Manager.instance.setMediaRecorderListener(this);
            vpInfo.setScanScroll(false);
            count = 4000;
            mHandler.sendEmptyMessageDelayed(0, 100);
        }catch (Exception e){
            e.printStackTrace();
            showMissingPermissionDialog();
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ListenRecordActivity.this);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startAppSettings();
            }
        });

        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    public String getBasePath() {
        String strPath = null;
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            strPath = getApplicationContext().getFilesDir() + "/" + "lameMp3";
        } else {
            strPath = Environment.getExternalStorageDirectory() + "/" + "lameMp3";
        }
        File dir = new File(strPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return strPath;
    }

    //结束录音
    public void stopRecord() {
        try {
            ivRecord.setVisibility(View.VISIBLE);
            ivRecordShow.setVisibility(View.GONE);
            LameMp3Manager.instance.stopRecorder();
            vpInfo.setScanScroll(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 播放，使用stream模式 + File.separator
     */
    private void playInModeStream() {
        MediaPlayUtil.init(getApplicationContext());
        MediaPlayUtil.playSound(getBasePath() + "/" + currentSelectPosition + bookId + "record.mp3", new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlay();
            }
        });
    }

    /**
     * 停止播放
     */
    private void stopPlay() {
        if (null != animationDrawable) {
            animationDrawable.stop();
        }
        ivVoice.setVisibility(View.VISIBLE);
        voiceRecond.setVisibility(View.GONE);
        MediaPlayUtil.release();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mHandler.hasMessages(0)) {
                mHandler.removeMessages(0);
            }
            switch (msg.what) {
                case 0:
                    if (count == 10000) {
                        count = 4000;
                    } else {
                        count = count + 500;
                    }
                    mHandler.sendEmptyMessageDelayed(0, 100);
                    ivRecordShow.getDrawable().setLevel(count);
                    break;
                case 1:
                    stopPlay();
                    break;
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(ListenRecordActivity.this);
                    errorPop.showPop("");
                    break;
                case 1010:
                    //这里代表录音完成
                    ivVoice.setImageResource(R.drawable.play_record_btn_press);
                    ivSubmit.setImageResource(R.mipmap.sure_bg);
                    vpInfo.setScanScroll(true);
                    break;
                case 100:
                    mRecordMusicService.goPlay();
                    break;
            }
        }
    };

}
